﻿using System;
using System.Diagnostics;
using System.Net;
using SSRSTestGenerator.Resources;

namespace SSRSTestGenerator.Controllers
{
    public class ValidateWebSerivce
    {
        public bool ServiceExists(string url, bool throwExceptions, out string errorMessage)
        {
            try
            {
                errorMessage = string.Empty;

                // try accessing the web service directly via it's URL
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;               
                request.UseDefaultCredentials = true; // if an exception - prompt for credentials            
                request.Timeout = 60000; // 1 minute

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                        throw new Exception(string.Format(LocalisedStrings.WebServiceValidationErrorMessageLocatingService, url));
                    else if (response.ContentLength < 1000 && response.ContentLength != -1) // content size doesn't look right (around 15850 bytes)
                        {
                            // throw error that will be caught in Exception below
                            throw new Exception();
                            // throw new Exception(string.Format(LocalisedStrings.WebServiceValidationErrorMessageLocatingService, url));                            
                        }
                }             
            }
            catch (WebException ex) // catches invalid server url
            {
                // decompose 400- codes here if you like
                errorMessage = string.Format(LocalisedStrings.WebServiceValidationErrorMessage, url, ex);
                Trace.TraceError(errorMessage);
                if (throwExceptions)
                    throw new Exception(errorMessage, ex);
                return false;
            }
            catch (Exception ex) // catches invalid service url (with the throw above)
            {
                errorMessage = string.Format(LocalisedStrings.WebServiceValidationErrorMessage, url, ex);
                Trace.TraceError(errorMessage);
                if (throwExceptions)
                    throw new Exception(errorMessage, ex);
                return false;
            }

            return true;
        }
    }
}
